/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on 01/07/2012, 16:17:20
 */
package sys.screen;

import java.awt.EventQueue;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import sys.bean.ParametrosBean;
import sys.dao.ParametrosDao;
import sys.dao.UsuarioDao;
import sys.utils.ConexaoADS;
import sys.utils.LetterUpper;
import sys.utils.Mensagens;
import sys.utils.Singleton;

public final class UILogin extends javax.swing.JFrame {

    //Relogio do Sistema
    private static final DateFormat formatoHora = new SimpleDateFormat("HH:mm:ss");

    SimpleDateFormat formatoData = new SimpleDateFormat("EE-dd/MM/yyyy");

    List<ParametrosBean> lista;

    public UILogin() {
        initComponents();
        this.setIconImage(new ImageIcon(getClass().getResource("/sys/picture/icon.png")).getImage());

        // Executar aplicaçao no meio da tela
        setLocationRelativeTo(null);
        setResizable(false);

        //Relogio do Sistema
        Thread clockThread = new Thread(new ClockRunnable(), "Clock thread");
        clockThread.setDaemon(true);
        clockThread.start();
        jlData.setText(formatoData.format(new Date()));

        atComboEmpresa();
        txLogin.requestFocus();
    }

    //Metodo Relogio do Sistema
    private JLabel getLblHora() {
        if (lblHora == null) {
            lblHora = new JLabel();
        }
        return lblHora;
    }

    //Metodo Relogio do Sistema
    public void setHora(Date date) {
        getLblHora().setText(formatoHora.format(date));
    }
    //Classe Para Mostrar Relogio do Sistema

    private class ClockRunnable implements Runnable {

        @Override
        public void run() {
            try {
                while (true) {
                    // Aqui chamamos o setHora através da EventQueue da AWT.  
                    // Conforme dito, isso garante Thread safety para o Swing.  
                    EventQueue.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            // Só podemos chamar setHora diretamente dessa  
                            // forma, pois esse Runnable é uma InnerClass não  
                            // estática.  
                            setHora(new Date());
                        }
                    });
                    // Fazemos nossa thread dormir por um segundo, liberando o  
                    // processador para outras threads processarem.  
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
            }
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txLogin = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txSenha = new javax.swing.JPasswordField();
        cbEmpresa = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        lblHora = new javax.swing.JLabel();
        jlData = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lbMsg = new javax.swing.JLabel();
        btnOk = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("LOGIN");
        setBackground(new java.awt.Color(255, 255, 255));

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true)));

        jLabel1.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel1.setText("EMPRESA:");

        txLogin.setDocument(new LetterUpper());
        txLogin.setBackground(new java.awt.Color(245, 245, 245));
        txLogin.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        txLogin.setForeground(new java.awt.Color(51, 51, 255));
        txLogin.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txLogin.setToolTipText("É possível logar tanto com nome de usuário, quanto com o código.");
        txLogin.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
        txLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txLoginActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel2.setText("SENHA:");

        txSenha.setBackground(new java.awt.Color(245, 245, 245));
        txSenha.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        txSenha.setForeground(new java.awt.Color(51, 51, 255));
        txSenha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txSenha.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
        txSenha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txSenhaActionPerformed(evt);
            }
        });

        cbEmpresa.setBackground(new java.awt.Color(204, 204, 204));
        cbEmpresa.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        cbEmpresa.setForeground(new java.awt.Color(51, 51, 255));

        jLabel4.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel4.setText("LOGIN:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cbEmpresa, javax.swing.GroupLayout.Alignment.LEADING, 0, 204, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txLogin, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txSenha))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50))
        );

        lblHora.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        lblHora.setForeground(new java.awt.Color(51, 51, 255));
        lblHora.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

        jlData.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jlData.setForeground(new java.awt.Color(51, 51, 255));
        jlData.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/login.png"))); // NOI18N

        lbMsg.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        lbMsg.setForeground(new java.awt.Color(255, 0, 0));

        btnOk.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/salvar.png"))); // NOI18N
        btnOk.setText("LOGIN");
        btnOk.setPreferredSize(new java.awt.Dimension(120, 30));
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addComponent(jLabel5)
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(104, 104, 104)
                        .addComponent(jlData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblHora, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(lbMsg, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnOk, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(37, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(lbMsg, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(16, 16, 16)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblHora, javax.swing.GroupLayout.DEFAULT_SIZE, 14, Short.MAX_VALUE)
                            .addComponent(jlData, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        jMenuBar1.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N

        jMenu1.setText("AJUDA");
        jMenu1.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        jMenuItem1.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jMenuItem1.setText("SOBRE");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed

        if (txLogin.getText().equals("")) {
            Mensagens.msgAtencao("campo usuário em branco");
            txLogin.requestFocus();
            txLogin.selectAll();
        } else {
            final BarraProgresso pb = new BarraProgresso(this);
            SwingWorker worker = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    pb.gerarJanela();
                    efetuaLogin();
                    return null;
                }
                @Override
                protected void done() {
                    pb.fechar();
                }
            };
            worker.execute();
        }
    }//GEN-LAST:event_btnOkActionPerformed

    private void txSenhaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txSenhaActionPerformed
        txSenha.selectAll();
        if (txLogin.getText().equals("")) {
            Mensagens.msgAtencao("campo usuário em branco");
            txLogin.requestFocus();
            txLogin.selectAll();
        } else {
            final BarraProgresso pb = new BarraProgresso(this);
            SwingWorker worker = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    pb.gerarJanela();
                    efetuaLogin();
                    return null;
                }

                @Override
                protected void done() {
                    pb.fechar();
                }
            };
            worker.execute();
        }
    }//GEN-LAST:event_txSenhaActionPerformed

    private void txLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txLoginActionPerformed
        txSenha.requestFocus();
    }//GEN-LAST:event_txLoginActionPerformed

    private void efetuaLogin() {
        try {

            ConexaoADS.section = lista.get(cbEmpresa.getSelectedIndex()).getBloco();
            Singleton.setBloco(lista.get(cbEmpresa.getSelectedIndex()).getBloco());

            if (UsuarioDao.efetuarLogin(txLogin.getText(), txSenha.getText())) {
                UITelaPrincipal telaPrincipal = new UITelaPrincipal();
                telaPrincipal.carregaPermissoesUsuario(Singleton.getCodigo());
                telaPrincipal.setVisible(true);
                this.dispose();

            } else {
                lbMsg.setText("USUÁRIO OU SENHA INVÁLIDOS!");
                txLogin.requestFocus();
            }
        } catch (SQLException | IOException ex) {
            Mensagens.msgAtencao("nao foi possivel conectar ao servidor,\nverifique os dados da conexao e altere se necessário!\n" + ex.getMessage());

            UIParametros tp = new UIParametros(this, true);
            tp.sessao = 0;
            tp.setVisible(true);
            this.dispose();
        }

    }

    public void atComboEmpresa() {
        try {
            lista = ParametrosDao.listaEmpresas();
            for (ParametrosBean param : lista) {
                cbEmpresa.addItem(param.getDescricao());
            }
        } catch (IOException ex) {
            Mensagens.msgErro("erro ao atualizar empresas\n" + ex.getMessage());
        }

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnOk;
    private javax.swing.JComboBox cbEmpresa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel jlData;
    private javax.swing.JLabel lbMsg;
    private javax.swing.JLabel lblHora;
    private javax.swing.JTextField txLogin;
    private javax.swing.JPasswordField txSenha;
    // End of variables declaration//GEN-END:variables
}
